package net.hvacapp.cmvrfforandroid.ui.project;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.manager.ProjectManager;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.MainTabBarActivity;
import net.hvacapp.cmvrfforandroid.ui.project.model.EquiptPriceData;
import net.hvacapp.cmvrfforandroid.ui.project.model.EquiptPriceGroupData;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetEquiptPriceDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectInfoData;
import net.hvacapp.cmvrfforandroid.ui.project.view.TwoLinesCellView;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.utils.NumberUtil;
import net.hvacapp.cmvrfforandroid.widget.CellSeperateLineView;
import net.hvacapp.cmvrfforandroid.widget.GroupSelectionView;
import net.hvacapp.cmvrfforandroid.widget.ProjectActionView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@EActivity(R.layout.activity_project_step8)
public class ProjectStep8Activity extends BaseActivity {

    @ViewById(R.id.action_view)
    ProjectActionView mActionView;


    private Dialog mProgressDlg;

    @ViewById(R.id.lv_templete)
    ListView mTempleteLv;

    private QuickAdapter<EquiptPriceGroupData> mQuickAdapter;


    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initViews();
        initEvent();
    }

    /***
     * 初始化视图
     */
    private void initViews() {
        mActionView.setActionInfo(ProjectManager.getInstance().getTotal(), ProjectManager.getInstance().getCurrent());
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        setupToolbar(R.string.title_for_project, "设备报价", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AnnotationUtil.get(MainTabBarActivity.class));
            }
        });
        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<EquiptPriceGroupData>(context, R.layout.group_selection_cell_item) {
                @Override
                protected void convert(final BaseAdapterHelper helper, final EquiptPriceGroupData item) {
                    final GroupSelectionView view = helper.getView(R.id.group_type);
                    view.setTitleString(item.getTag());
                    view.setInfoString("");
                    view.setGroupVisible(item.isExpand());
                    if (item.isExpand()) {
                        helper.setVisible(R.id.ll_content, true);
                    }
                    else {
                        helper.setVisible(R.id.ll_content, false);
                    }
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            item.setExpand(!item.isExpand());
                            view.setGroupVisible(item.isExpand());
                            if (item.isExpand()) {
                                helper.setVisible(R.id.ll_content, true);
                            } else {
                                helper.setVisible(R.id.ll_content, false);
                            }
                        }
                    });

                    LinearLayout contentLl = helper.getView(R.id.ll_content);
                    contentLl.removeAllViews();
                    for (final EquiptPriceData eItem : item.getDatas()) {
                        CellSeperateLineView line = new CellSeperateLineView(ProjectStep8Activity.this);
                        contentLl.addView(line);

                        final TwoLinesCellView itemView = new TwoLinesCellView(ProjectStep8Activity.this);
                        itemView.setTitleString(eItem.getXh());
                        String desc = eItem.getCount() + "台 " + eItem.getPrice() + "元/台";
                        itemView.setDescString(desc);
                        itemView.setItemSelected(true);
                        itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //编辑价格
                                String title = eItem.getXh() + "\n最新报价：" + eItem.getPrice() + "元";
                                editPrice(eItem, title);
                            }
                        });
                        contentLl.addView(itemView);
                    }
                }
            };
        }
        mTempleteLv.setAdapter(mQuickAdapter);
    }

    private void editPrice(final EquiptPriceData data, String title) {
        final EditText priceEt = new EditText(this);
        priceEt.setKeyListener(new DigitsKeyListener(false,true));
        priceEt.setText(NumberUtil.formateDouble(data.getPrice()));
        new AlertDialog.Builder(this).setTitle(title)
                .setView(priceEt)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            double price = Double.valueOf(priceEt.getText().toString());
                            if (price > 0) {
                                //修改报价
                                data.setPrice(price);

                                modifyEquiptPriceData(data);
                            }
                            else {
                                showMessage("设备价格不能为0");
                            }
                        }
                        catch (Exception e) {

                        }
                    }
                })

                .setNegativeButton("取消", null)
                .show();
    }


    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        loadProjectPriceInfo();
    }



    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    private void initEvent() {
        mActionView.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上一步
                ProjectManager.getInstance().goLastStep();
                finish();
            }
        });

        mActionView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下一步
                ProjectManager.getInstance().goNextStep();
                startActivity(AnnotationUtil.get(ProjectStep9Activity.class));
            }
        });


    }


    /**
     *  获取项目中设备报价信息
     */
    private void loadProjectPriceInfo() {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());

        mProgressDlg = createProgressBarDialog(this, "数据加载中...");
        mProgressDlg.show();

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_ALL_DEVICE_PRICE, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetEquiptPriceDataResp>() {
            @Override
            public void onSuccess(GetEquiptPriceDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                if (obj != null && obj.getGetEquipPricesResult() != null) {
                    EquiptPriceGroupData snjData = new EquiptPriceGroupData();
                    snjData.setTag("室内机");
                    snjData.setDatas(new ArrayList<EquiptPriceData>());

                    EquiptPriceGroupData swjData = new EquiptPriceGroupData();
                    swjData.setTag("室外机");
                    swjData.setDatas(new ArrayList<EquiptPriceData>());

                    EquiptPriceGroupData qxsyktData = new EquiptPriceGroupData();
                    qxsyktData.setTag("轻型商用空调");
                    qxsyktData.setDatas(new ArrayList<EquiptPriceData>());

                    EquiptPriceGroupData qrjhqData = new EquiptPriceGroupData();
                    qrjhqData.setTag("全热交换器");
                    qrjhqData.setDatas(new ArrayList<EquiptPriceData>());

                    EquiptPriceGroupData kqnrsjData = new EquiptPriceGroupData();
                    kqnrsjData.setTag("空气能热水机");
                    kqnrsjData.setDatas(new ArrayList<EquiptPriceData>());

                    for (EquiptPriceData item : obj.getGetEquipPricesResult()) {
                        if (StringUtils.isEquals(item.getEquipTag(), ProjectInfoData.MACHINE_TAG_FOR_SNJ)) {
                            snjData.setExpand(true);
                            snjData.getDatas().add(item);
                        } else if (StringUtils.isEquals(item.getEquipTag(), ProjectInfoData.MACHINE_TAG_FOR_SWJ)) {
                            swjData.setExpand(true);
                            swjData.getDatas().add(item);
                        } else if (StringUtils.isEquals(item.getEquipTag(), ProjectInfoData.MACHINE_TAG_FOR_QXSYKT)) {
                            qxsyktData.setExpand(true);
                            qxsyktData.getDatas().add(item);
                        } else if (StringUtils.isEquals(item.getEquipTag(), ProjectInfoData.MACHINE_TAG_FOR_QRJHQ)) {
                            qrjhqData.setExpand(true);
                            qrjhqData.getDatas().add(item);
                        } else if (StringUtils.isEquals(item.getEquipTag(), ProjectInfoData.MACHINE_TAG_FOR_KQNRSJ)) {
                            kqnrsjData.setExpand(true);
                            kqnrsjData.getDatas().add(item);
                        }
                    }
                    if (snjData.getDatas().size() > 0) {
                        mQuickAdapter.add(snjData);
                    }
                    if (swjData.getDatas().size() > 0) {
                        mQuickAdapter.add(swjData);
                    }
                    if (qxsyktData.getDatas().size() > 0) {
                        mQuickAdapter.add(qxsyktData);
                    }
                    if (qrjhqData.getDatas().size() > 0) {
                        mQuickAdapter.add(qrjhqData);
                    }
                    if (kqnrsjData.getDatas().size() > 0) {
                        mQuickAdapter.add(kqnrsjData);
                    }
                }
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("获取空气能热水机信息失败，请重试！");
            }
        });

    }

    /**
     * 修改设备报价信息
     * @param data
     */
    private void modifyEquiptPriceData(EquiptPriceData data) {
        Map<String, Object> param = new HashMap<>();
        param.put("equipPriceData", data);

        BasicHttpClient.httpPostAsync(HttpConstant.HTTP_POST_PROJECT_ONE_DEVICE_PRICE, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetEquiptPriceDataResp>() {
            @Override
            public void onSuccess(GetEquiptPriceDataResp obj) {
                //需要重新拉取所有的系统数据
                mQuickAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(String response) {
                showMessage("报价修改失败！");
            }
        });

    }


}
